using System.Reflection;
using DealerPlatform.Domain;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace DealerPlatform.Extensions;

public static class ServiceCollectionExtensions
{
    public static IServiceCollection RepositoryRegister(this IServiceCollection services)
    {
        var asmCore = Assembly.Load("DealerPlatform.Core");
        var implementationType = asmCore.GetTypes().FirstOrDefault(x => x.Name == "Repository`1");
        var interfaceType = implementationType.GetInterface("IRepository`1").GetGenericTypeDefinition();
        services.AddTransient(interfaceType, implementationType);
        return services;
    }

    public static IServiceCollection ServiceRegister(this IServiceCollection services)
    {
        List<Assembly> assemblys = new();
        
        var provider = services.BuildServiceProvider();
        var configuration = provider.GetService<IConfiguration>();
        var classes = configuration["IocClasses"].Split(",").ToList();
        
        classes.ForEach(c =>
        {
            assemblys.Add(Assembly.Load(c));
        });
        
        // var asmService = Assembly.Load("DealerPlatform.Service");
        // var asmRedisWorker = Assembly.Load("DealerPlatform.Common");
        // assemblys.Add(asmService);
        // assemblys.Add(asmRedisWorker);
        
        foreach (var assembly in assemblys)
        {
            var implementationTypes = assembly.GetTypes().Where(
                x => x.IsAssignableTo(typeof(IOcTag)) &&
                     !x.IsAbstract &&
                     !x.IsInterface);
            foreach (var implementationType in implementationTypes)
            {
                // var inter = implementationType.GetInterfaces();
                var interfaceType = implementationType.GetInterfaces().Where(
                    x => x != typeof(IOcTag)).FirstOrDefault();
                services.AddTransient(interfaceType, implementationType);
            }
        }

        return services;
    }
}